package com.example.demo.main.rabbitmq.message;

import com.example.demo.main.rabbitmq.utils.RabbitmqConnectionUtil;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author xieluoyin
 */
public class Consumer {

    public static void main(String[] args) throws Exception {


        Connection connection = RabbitmqConnectionUtil.getConnection();

        //通过connection创建一个Channel
        Channel channel = connection.createChannel();

        //声明（创建）一个队列
        String queueName = "test001";
        channel.queueDeclare(queueName, true, false, false, null);


        com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println(" [Consumer] Received '" + message + "'");

                Map<String, Object> headers = properties.getHeaders();
                System.err.println("headers get my1 value: " + headers.get("my1"));
            }
        };

        //参数：队列名称、是否自动ACK、Consumer
        channel.basicConsume(queueName, true, consumer);
    }
}
